package com.zelin.dao.impl;

import com.zelin.dao.UserDao;
import com.zelin.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * ------------------------------
 * 功能：
 * 作者：WF
 * 微信：hbxfwf13590332912
 * 创建时间：2021/10/14-14:25
 * ------------------------------
 */
@Repository
public class UserDaoImpl implements UserDao,RowMapper<User> {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    // Resultset---》List<Student>
    //1. 查询所有用户
    @Override
    public List<User> findAll() {
        return jdbcTemplate.query("select * from user", this);
    }

    //2. 根据id查询 用户
    @Override
    public User findById(int id) {
        return jdbcTemplate.queryForObject("select * from user where id=?",this,id);
    }

    //3. 修改用户
    @Override
    public void update(User user) {
        jdbcTemplate.update("update user set username=?,balance=? where id=?",
                                user.getUsername(),
                                user.getBalance(),
                                user.getId());
    }

    // 修改账户金额
    @Override
    public void updateAccount(int from, int money) {
        jdbcTemplate.update("update user set balance=balance-? where id=?",money,from);
    }

    //4. 处理结果集与当前实体类的映射
    @Override
    public User mapRow(ResultSet rs, int i) throws SQLException {
        return new User(rs.getInt("id"),
                rs.getString("username"),
                rs.getDouble("balance"));
    }
}
